<script setup>
import { ref, onMounted, provide, computed, onUnmounted } from 'vue'
import { RouterView, useRouter, useRoute } from 'vue-router'
import { Calendar, User, List, ArrowDown, SwitchButton } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getToken, getEmail, removeToken, removeEmail } from '@/utils/cookies'
import { getUserInfo } from '@/api/user'

const router = useRouter()
const route = useRoute()
const isLoggedIn = ref(false)
const userEmail = ref('')

// 添加移动端判断
const windowWidth = ref(window.innerWidth)
const isMobile = computed(() => windowWidth.value <= 768)

// 添加当前激活的菜单项计算属性
const activeMenu = computed(() => {
  const { path } = route
  if (path === '/profile') {
    return '/profile'
  }
  return path
})

// 监听窗口大小变化
const handleResize = () => {
  windowWidth.value = window.innerWidth
}

// 检查登录状态
const checkLoginStatus = async () => { 
  const token = getToken()
  if (token) {
    try {
      // 获取最新的用户信息
      const userInfo = await getUserInfo()
      isLoggedIn.value = true
      userEmail.value = userInfo.email
    } catch (error) {
      // 如果获取用户信息失败，说明token可能已失效
      console.error('获取用户信息失败:', error)
      removeToken()
      removeEmail()
      isLoggedIn.value = false
      userEmail.value = ''
    }
  } else {
    isLoggedIn.value = false
    userEmail.value = ''
  }
}

// 提供给子组件使用
provide('updateLoginStatus', checkLoginStatus)

// 初始检查登录状态
onMounted(() => {
  checkLoginStatus()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

const handleLogout = () => {
  removeToken()
  removeEmail()
  isLoggedIn.value = false
  userEmail.value = ''
  ElMessage.success('已退出登录')
  router.push('/')
}
</script>

<template>
  <el-container class="layout-container">
    <el-header>
      <div class="nav-container">
        <div class="left-section">
          <router-link to="/" class="logo-section">
            <el-icon :size="isMobile ? 20 : 24"><Calendar /></el-icon>
            <h1 v-if="!isMobile">TodoList</h1>
          </router-link>
          <el-menu 
            mode="horizontal" 
            :router="true" 
            class="nav-menu"
            :ellipsis="false"
            :size="isMobile ? 'large' : 'default'"
            :default-active="activeMenu"
          >
            <el-menu-item index="/">首页</el-menu-item>
            <el-menu-item index="/todos">待办事项</el-menu-item>
            <el-menu-item index="/profile" style="display: none;">个人中心</el-menu-item>
          </el-menu>
        </div>

        <div class="right-section">
          <template v-if="!isLoggedIn">
            <el-dropdown v-if="isMobile">
              <el-button :size="isMobile ? 'large' : 'default'" circle>
                <el-icon><User /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="$router.push('/login')">
                    登录
                  </el-dropdown-item>
                  <el-dropdown-item @click="$router.push('/register')">
                    注册
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <template v-else>
              <el-button 
                :size="isMobile ? 'large' : 'default'"
                @click="$router.push('/login')"
              >
                登录
              </el-button>
              <el-button 
                type="primary" 
                :size="isMobile ? 'large' : 'default'"
                @click="$router.push('/register')"
              >
                注册
              </el-button>
            </template>
          </template>
          <template v-else>
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                <el-avatar :size="32" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <span class="dropdown-email">{{ userEmail }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="$router.push('/profile')">
                    <el-icon><User /></el-icon>个人中心
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">
                    <el-icon><SwitchButton /></el-icon>退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </div>
      </div>
    </el-header>
    
    <el-main>
      <RouterView />
    </el-main>

    <el-footer height="auto">
      <div class="footer-content">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="8" class="footer-section">
            <h3>关于我们</h3>
            <p>Todo List 是一个简单而强大的待办事项管理工具，帮助您更好地组织工作和生活。</p>
          </el-col>
          <el-col :xs="24" :sm="8" class="footer-section">
            <h3>快速链接</h3>
            <ul>
              <li><router-link to="/">首页</router-link></li>
              <li><router-link to="/todos">待办事项</router-link></li>
              <li><a href="#" @click.prevent>帮助中心</a></li>
              <li><a href="#" @click.prevent>联系我们</a></li>
            </ul>
          </el-col>
          <el-col :xs="24" :sm="8" class="footer-section">
            <h3>联系方式</h3>
            <p>邮箱：support@todolist.com</p>
            <p>地址：中国，北京市</p>
          </el-col>
        </el-row>
      </div>
      <div class="footer-bottom">
        <p>&copy; {{ new Date().getFullYear() }} Todo List. All rights reserved.</p>
      </div>
    </el-footer>
  </el-container>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.layout-container {
  min-height: 100vh;
}

.el-header {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  position: fixed;
  width: 100%;
  z-index: 100;
  background: white;
}

.nav-container {
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 20px;
  overflow: hidden;
  flex: 1;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 10px;
  text-decoration: none;
  color: inherit;
  white-space: nowrap;
  min-width: fit-content;
}

.logo-section h1 {
  font-size: 1.5rem;
  margin: 0;
}

.nav-menu {
  border: none;
  min-width: 0;
  flex: 1;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: fit-content;
  margin-left: 20px;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.dropdown-email {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  color: #606266;
  font-size: 14px;
}

:deep(.el-dropdown-menu__item) {
  min-width: 160px;
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  margin-right: 0;
}

.footer-content {
  padding: 40px 20px;
  background: #f5f7fa;
}

.footer-section {
  margin-bottom: 20px;
}

.footer-section h3 {
  margin-bottom: 15px;
  color: #303133;
}

.footer-section ul {
  list-style: none;
  padding: 0;
}

.footer-section ul li {
  margin-bottom: 10px;
}

.footer-section a {
  color: #606266;
  text-decoration: none;
}

.footer-section a:hover {
  color: #409EFF;
}

.footer-bottom {
  text-align: center;
  padding: 20px;
  background: #ebeef5;
  color: #909399;
}

@media (max-width: 768px) {
  .nav-container {
    padding: 0 10px;
  }

  .left-section {
    gap: 10px;
  }

  .nav-menu {
    padding-left: 5px;
  }

  .el-menu-item {
    padding: 0 10px;
  }

  .right-section {
    gap: 5px;
    margin-left: 10px;
  }
}
</style>
